<?php
require_once "services/FacebookProxy.php";
require_once "data/dao/FriendCodeDAO.php";
require_once "data/dao/GameDAO.php";
require_once "application/user/User.php";
require_once "application/user/Friend.php";
require_once "www/_include/smarty/libs/Smarty.class.php";
require_once "data/dao/UserDAO.php";
require_once "data/dao/CollectionDAO.php";
require_once "utils/HTTPRequest.php";

class FindFriends{
	
	private $smarty;
	private $user;
	private $facebook;
	
	private $gameId = null;
	
	public function FindFriends(){
		
		$this->smarty = new Smarty();
		$this->facebook = new FacebookProxy();
		$this->facebook->requireFrame();
		$this->user = $this->facebook->requireLogin();
		
		$viewType = HTTPRequest::getParam("do");
		
		if($viewType == "find-friends")
			$this->gameId = HTTPRequest::getParam("game-id");
		
		$this->getPlaceholderValues($viewType);
		$this->renderPage();
	}
	
	private function getPlaceholderValues($viewType){
		
		if($viewType == "find-friends"){
			$this->smarty->assign("numberOfUsers", count($this->findPlayers($this->user, $this->gameId)));
			$this->smarty->assign("friends", $this->findPlayers($this->user, $this->gameId));		
			$this->smarty->assign("game", $this->getGameName($this->gameId));
			$this->smarty->assign("gameId", $this->gameId);
			$this->smarty->assign("findFriends", true);
		}
		if($viewType == "display-friends"){
//			$this->smarty->assign("numberOfUsers", count($this->findAllFriends($this->user)));
			$this->smarty->assign("friends", $this->findAllFriends($this->user));		
			$this->smarty->assign("myFriends", true);
			$this->smarty->assign("user", $this->user);
			$this->smarty->assign("activePage", $_REQUEST['page']);
		}

		$this->smarty->assign("styleSheet", file_get_contents("html/wiiSocial.css"));
		$this->smarty->assign("HOST", HOST_URL);
	}
	
	private function renderPage(){
		
		$this->smarty->display("friends.tpl");
	}
	
	private function getGameName($gameId){
		
		$gdao = new GameDAO();
		$game = $gdao->getGame($gameId);
		return $game->getTitle();
	}
	
	/**
	 * this function finds all the online players for a given game
	 */
	private function findPlayers($userId, $gameId){
		
		$page = $_REQUEST['page'];
		
		// allows pagination
		$pageNo = $_REQUEST['page'];

		$fcdao = new FriendCodeDAO();
		$gdao = new GameDAO();

		$friendResultsView = $fcdao->findFriendsForGame($gameId, $userId, $gdao->getGame($gameId)->getTitle(), $page);
		//render smarty templates
		//TODO: move out of this method
		$this->smarty->assign("numberOfUsers", $friendResultsView->getTotalFriends());
		$this->smarty->assign("totalPages", $friendResultsView->getLastPage());
		$this->smarty->assign("pagination", range(1, $friendResultsView->getLastPage()));
		
		$users = $friendResultsView->getFriends();
				
		if($users == null)
			return false;

		$userDetails = array();
		
		for($i=0; $i<count($users);$i++){

			$game = $gdao->getGame($this->gameId);
			$friendCodeGameMap = array(array('game' => $game->getTitle(),
													 'friend_code' => $users[$i]['friend_code']));
			$udao = new UserDAO();
			$friend = $udao->findUser($users[$i]['user_id']);

			array_push($userDetails, new Friend($users[$i]['user_id'], 
				$friend->getFirstName(), $friend->getLastName(), 
				$friend->getProfilePicSmallUrl(), $friend->getProfilePicBigUrl(), 
				$friend->getWiiCode(), $friendCodeGameMap, false));
		}
		return $userDetails;
	}
	
	/**
	 * this function finds all of the online players that the user
	 * can challenge, for all the games they own
	 */
	private function findAllFriends($userId){
		
		// no friends can be found if the user has no games
		if(CollectionUtils::collectionIsEmpty($this->user)){
			return null;
		}

		// allows pagination
		$pageNo = $_REQUEST['page'];
		
		$cdao = new CollectionDAO();
		$udao = new UserDAO();
		$fcdao = new FriendCodeDAO();
		$gdao = new GameDAO();
		
		// get users games list
		$usersCollection = $cdao->getCollection($userId);
		$usersGames = $usersCollection->getGames();

		// this will contain an array of Friend objects
		$friends = array();

		// finds users that have the same games
		$friendResultsView = $cdao->findUsersThatHaveGameInCollection($usersGames, $pageNo);
		$friendsWithGamesInCollection = $friendResultsView->getFriends();
		
		//render smarty templates
		//TODO: move out of this method
		$this->smarty->assign("numberOfUsers", $friendResultsView->getTotalFriends());
		$this->smarty->assign("totalPages", $friendResultsView->getLastPage());
		$this->smarty->assign("pagination", range(1, $friendResultsView->getLastPage()));
		
		foreach($friendsWithGamesInCollection as $f){
			
			$userWithGame = $udao->findUser($f['user_id']);
			$friendCodeGameMap = array();		

			foreach (explode(",", $f['collection']) as $game){
				// get friendcode
				$friendCode = $fcdao->findFriendCode($f['user_id'], $game);
				// get game object
				$game = $gdao->getGame($game);
				array_push($friendCodeGameMap, array('game' => $game->getTitle(),
													 'friend_code' => $friendCode));
			}
			
			/* if the facebook user is a friend of the logged in user
			 * put the user at the beginning of the array, this places
			 * all of a users 'real' facebook friends at beginning of list.
			 * - matt 080329
			 */	
			//
			//TODO: dont call the facebook functions they just break the app!
			// store users friends in database
			//
			/*if($this->facebook->areFriends($this->user, $f['user_id'])){
				array_unshift($friends, new Friend($f['user_id'], 
					$userWithGame->getFirstName(), $userWithGame->getLastName(),
					$userWithGame->getProfilePicSmallUrl(), $userWithGame->getProfilePicBigUrl(), 
					$userWithGame->getWiiCode(), $friendCodeGameMap, true));
			}
			else{*/
				array_push($friends, new Friend($f['user_id'], 
					$userWithGame->getFirstName(), $userWithGame->getLastName(),
					$userWithGame->getProfilePicSmallUrl(), $userWithGame->getProfilePicBigUrl(), 
					$userWithGame->getWiiCode(), $userWithGame->getLocationISO3166A2(), 
					$userWithGame->getStoreLocation(), $friendCodeGameMap, false));
//			}
		}
		return $friends;
	}
			

	/**
	 * array returned from facebook method is passed to
	 * this method, along with the user id.  It will then
	 * search the facebook info array, and return the details
	 * for the specified user
	 * 
	 * @param $fbusers array from facebook method
	 * @param $uid user to search for
	 * 
	 * @return array of specified users facebook details
	 */
	private function getFacebookUsersDetails($fbusers, $uid){

		for($i=0;$i<count($fbusers); $i++){

			if ($fbusers[$i]['uid'] == $uid)
				return $fbusers[$i];
		}		
	}
}
$ff = new FindFriends();
?>
